package com.sample.springbootsample.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @projectName: spring-boot-sample
 * @description:
 * @author: Adam
 * @create: 2019-12-19 19:16
 **/

@Configuration
public class RabbitMqConfig {


    //消息确认回调函数
    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){
         RabbitTemplate rabbitTemplate = new RabbitTemplate();
         rabbitTemplate.setConnectionFactory(connectionFactory);
        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);

        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("ConfirmCallback:     "+"相关数据："+correlationData);
                System.out.println("ConfirmCallback:     "+"确认情况："+ack);
                System.out.println("ConfirmCallback:     "+"原因："+cause);
            }
        });

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

                System.out.println("ReturnCallback:     "+"消息："+message);
                System.out.println("ReturnCallback:     "+"回应码："+replyCode);
                System.out.println("ReturnCallback:     "+"回应信息："+replyText);
                System.out.println("ReturnCallback:     "+"交换机："+exchange);
                System.out.println("ReturnCallback:     "+"路由键："+routingKey);
            }
        });

        return rabbitTemplate;
    }

    @Bean
    public Queue TestDirectQueue(){
        return new Queue("TestDirectQueue",true);
    }

    @Bean
    public Queue TestDirectQueue1(){
        return new Queue("TestDirectQueue1",true);
    }


    @Bean
    public DirectExchange TestDirectExchange(){
        return new DirectExchange("TestDirectExchange");
    }


    //创建了队列，但是并没有进行绑定。
    //只要队列名称和生产者的routingKey相等且生产者没有自定义交换机，而是采用默认交换机，就不用绑定也可接收到。
    @Bean
    public Queue Queue(){
        return new Queue("testRoutingKey");
    }

    //绑定
    @Bean
    public Binding bindingDirect(){
        return BindingBuilder.bind(TestDirectQueue()).to(TestDirectExchange()).with("TestDirectBinding");
    }

    @Bean
    public Binding bindingTest(){
        return BindingBuilder.bind(Queue()).to(TestDirectExchange()).with("testRoutingKey");
    }
}
